﻿using NetCoreCMS.DTO;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NetCoreCMS.Common
{
    public class WXTokenHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="redisName"></param>
        /// <param name="app"></param>
        /// <param name="shareUrl">https://www/user?name=13</param>
        /// <returns></returns>
        public static AccessTokenModel GetAccessToken(string redisName,Models.User_oauth_app app,string shareUrl)
        {
            AccessTokenModel acmodel = new AccessTokenModel();
            try
            {            
            #region ticket
            string ticket = "";
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
            {
                IDatabase db = redis.GetDatabase();
                #region getAccessToken
                string access_token = "";
                string json = db.StringGet(redisName + "accessToken");
                if (!string.IsNullOrEmpty(json))//不为空 开始反序列化
                {
                    try
                    {
                        access_token = json;
                    }
                    catch (Exception)//反序失败就查
                    {
                        #region 查
                        string requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + app.oauth_app_id + "&secret=" + app.oauth_app_key;
                        var response = Utils.GetURLResponse(requestUrl);
                        //{"access_token":"ACCESS_TOKEN","expires_in":7200}
                        string result = "";
                        using (Stream receiveStream = response.GetResponseStream())
                        {

                            using (StreamReader readerOfStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8))
                            {
                                result = readerOfStream.ReadToEnd();
                            }
                        }
                        var openModel = JsonConvert.DeserializeObject<WeiXinOpenIdModel>(result);
                        json = openModel.access_token;
                        #endregion
                        db.StringSet(redisName + "accessToken", json, new TimeSpan(7200 * TimeSpan.TicksPerSecond));
                        access_token = json;
                    }
                }
                else//为空，查，序列化,存;
                {
                    #region 查
                    string requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + app.oauth_app_id + "&secret=" + app.oauth_app_key;
                    var response = Utils.GetURLResponse(requestUrl);
                    //{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    string result = "";
                    using (Stream receiveStream = response.GetResponseStream())
                    {

                        using (StreamReader readerOfStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8))
                        {
                            result = readerOfStream.ReadToEnd();
                        }
                    }
                    var openModel = JsonConvert.DeserializeObject<WeiXinOpenIdModel>(result);
                    json = openModel.access_token;
                    #endregion
                    db.StringSet(redisName + "accessToken", json, new TimeSpan(7200 * TimeSpan.TicksPerSecond));
                    access_token = json;
                }
                #endregion
                #region getTicket                
                string json2 = db.StringGet(redisName + "jsapiTicket");
                if (!string.IsNullOrEmpty(json2))//不为空 开始反序列化
                {
                    try
                    {
                        ticket = json2;
                    }
                    catch (Exception)//反序失败就查
                    {
                        #region 查
                        string requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
                        var response = Utils.GetURLResponse(requestUrl);
                        //{"access_token":"ACCESS_TOKEN","expires_in":7200}
                        string result = "";
                        using (Stream receiveStream = response.GetResponseStream())
                        {

                            using (StreamReader readerOfStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8))
                            {
                                result = readerOfStream.ReadToEnd();
                            }
                        }
                        var openModel = JsonConvert.DeserializeObject<DTO.TicketModel>(result);
                        json2 = openModel.ticket;
                        #endregion
                        db.StringSet(redisName + "jsapiTicket", json2, new TimeSpan(7200 * TimeSpan.TicksPerSecond));
                        ticket = json2;
                    }
                }
                else//为空，查，序列化,存;
                {
                    #region 查
                    string requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
                    var response = Utils.GetURLResponse(requestUrl);
                    //{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    string result = "";
                    using (Stream receiveStream = response.GetResponseStream())
                    {

                        using (StreamReader readerOfStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8))
                        {
                            result = readerOfStream.ReadToEnd();
                        }
                    }
                    var openModel = JsonConvert.DeserializeObject<DTO.TicketModel>(result);
                    json2 = openModel.ticket;
                    #endregion
                    db.StringSet(redisName + "jsapiTicket", json2, new TimeSpan(7200 * TimeSpan.TicksPerSecond));
                    ticket = json2;
                }
                #endregion
            }
            #endregion
            #region wx            
            acmodel.noncestr = Utils.SHA1Encrypt("idcurl");
            acmodel.jsapi_ticket = ticket;
            string jmdata = "jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}";
            jmdata = string.Format(jmdata, ticket, acmodel.noncestr, acmodel.ts, shareUrl);
            acmodel.signature = Utils.SHA1Encrypt(jmdata);
                #endregion
            }
            catch (Exception)
            {

            }
            return acmodel;
        }
    }
}
